from control.models import *
from basic_component_related_management.models import *
import pandas as pd
from django.db import IntegrityError, transaction
import json
from tqdm import tqdm
import traceback
from datetime import datetime
from unit_management.models import *


def init_property_group():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    unit_file_path = "files/basic_data_init_final_v2/A076. PCdata基表-4-物质性质表（20250403R1）-0版.xlsx"
    # unit_file_path = "files/basic_data_init_final_v2/基表20250306/A075test.xlsx"
    sheet_name = "物质性质表"
    df = pd.read_excel(unit_file_path, sheet_name=sheet_name, header=2, dtype=str)
    start_row = 0
    end_row = 435
    # end_row = 13
    num_columns = 3
    selected_data = df.iloc[start_row:, :num_columns].fillna("")
    property_group_list = []
    for index,row in selected_data.iterrows():
        if row["nPropertyGroupID"]!="":
            property_group_list.append(
                {
                    "nPropertyGroupID":row["nPropertyGroupID"],
                    "sPropertyGroup":row["sPropertyGroup"],
                    "sPropertyGroupCN":row["sPropertyGroupCN"]
                }
            )
    for item in property_group_list:
        PropertyGroup.objects.create(
            name=item["sPropertyGroupCN"],
            name_en=item["sPropertyGroup"],
            sei_id = item["nPropertyGroupID"],
            is_pure_used = True,
            is_binary_used = True,
            is_ternary_used = True,
            is_multi_used = True,
            is_reaction_used = True,
            is_complex_used = True,
            create_person=super_admin_entity,
            modify_person=super_admin_entity
        )   


def init_property():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    unit_file_path = "files/basic_data_init_final_v2/A076. PCdata基表-4-物质性质表（20250403R1）-0版.xlsx"
    # unit_file_path = "files/basic_data_init_final_v2/基表20250306/A075test.xlsx"
    sheet_name = "物质性质表"
    df = pd.read_excel(unit_file_path, sheet_name=sheet_name, header=2, dtype=str)
    start_row = 0
    end_row = 435
    num_columns = 16
    selected_data = df.iloc[start_row:, :num_columns].fillna("")

    property_entity_list = []
    property_group_id = ""
    property_group_entity=None
    property_id_set = set()

    # 创建量叫做未找到，标识物性绑定时没找到这个量
    quantity_miss_entity = Quantity.objects.filter(quantity_name="未找到的量").first()
    if quantity_miss_entity is None:
        quantity_miss_entity = Quantity.objects.create(
            quantity_name = "未找到的量",
            quantity_name_en = "miss quantity",
            sei_id = "miss",
            dimension = Dimension.objects.filter(dimension_name="无量纲").first(),
            quantity_description = "创建量叫做未找到，标识物性绑定时没找到这个量",
            create_person = super_admin_entity,
            modify_person = super_admin_entity
        )

    for index,row in selected_data.iterrows():
        # print(index,row["ePropNameCN"])
        if row["nPCdataPropID"] in property_id_set:
            continue
        else:
            property_id_set.add(row["nPCdataPropID"])
        if row["nPropertyGroupID"]!="":
            property_group_id = row["nPropertyGroupID"]
            property_group_entity = PropertyGroup.objects.filter(sei_id=row["nPropertyGroupID"]).first()
        # if row["nQuantityID\n量ID"] == "":
        #     print("block")
            
        quantity_entity = Quantity.objects.filter(quantity_abbreviation=row["sQuantityAbb"]).first()
        # if quantity_entity is None:
            # print("miss quantity",row["nQuantityID\n量ID"])
        if quantity_entity is None:
            quantity_entity = quantity_miss_entity
            # print("miss quantity",row)
            # return 
        property_item={
            "name":row["ePropNameCN"],
            "name_en":row["ePropName"],
            "abbreviation":row["ePropAbbreviation"],
            "symbol":row["ePropSymbol"],
            "symbol_latex":row["sPropSymbol\n（LATEX）"],
            "property_group":property_group_entity,
            "sei_id":row["nPCdataPropID"],
            "symbol_mathml":row["sPropSymbol\n（MathML）"],
            "description":row["sPropDescription\n参考描述"],
            "quantity":quantity_entity,
            "is_single_value" :True,
            "is_fixed_value" :True,
            "is_one_variable" :True,
            "is_two_variable" :True,
            "is_multi_variable" :True,
            "is_reaction" :True,
            "create_person":super_admin_entity,
            "modify_person":super_admin_entity
        }

        property_entity_list.append(Property(**property_item))
    print(len(property_entity_list))

    try:
        with transaction.atomic():
            Property.objects.bulk_create(property_entity_list)
            # raise Exception("rollback")
    except Exception as e:
        traceback.print_exc()        



    

def init_property_content():

    init_property_group()
    init_property()

    print("finish property ")